package com.dgut.staffmodule.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dgut.staffmodule.dao.DepartmentRepository;
import com.dgut.staffmodule.dao.StaffRepository;
import com.dgut.staffmodule.entity.Department;
import com.dgut.staffmodule.entity.Staff;
import com.dgut.staffmodule.entity.StaffEditDTO;
import com.dgut.usermodule.entity.User;
import com.dgut.usermodule.service.UserService;

@Service
@Transactional
public class StaffService implements IStaffService {
	@Autowired
	private StaffRepository staffRepository;// 员工dao
	@Autowired
	private DepartmentRepository departmentRepository;// 部门dao
	@Autowired
	private UserService userService;// 用户service

	// 保存员工
	public boolean saveOrUpdate(Staff staff) {// ,Long departmentId
		Department department = new Department();
		department = departmentRepository.findOne(staff.getDepartment().getId());
		staff.setDepartment(department);
		department.getStaffs().add(staff);
		User user = new User();// 新增员工时设置员工的用户
		user.setUserName(staff.getStaffName());
		user.setPassword(staff.getPassword());
		user.setPhone(staff.getPhone());
		user.setDate(new Date());
		String res = userService.save(user);
		if (res == "用户名重复！") {
			return false;
		} else {
			staffRepository.save(staff);
			return true;
		}

	}

	//转换学历
	public String convertEducation(String education) {
		if(education.equals("A")) {
			education = "小学";
		}
		if(education.equals("B")) {
			education = "初中";
		}
		if(education.equals("C")) {
			education = "高中";
		}
		if(education.equals("D")) {
			education = "大专";
		}
		if(education.equals("E")) {
			education = "本科";
		}
		if(education.equals("F")) {
			education = "研究生";
		}
		if(education.equals("G")) {
			education = "硕士";
		}
		if(education.equals("H")) {
			education = "博士";
		}
		return education;
	}
	
	//通过出生日期获取年龄
	public int getAgeByBirth(Date dateOfBirth) {
		int age = 0;
		Calendar born = Calendar.getInstance();
		Calendar now = Calendar.getInstance();
		if (dateOfBirth != null) {
			now.setTime(new Date());
			born.setTime(dateOfBirth);
			if (born.after(now)) {
				throw new IllegalArgumentException("年龄不能超过当前日期");
			}
			age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);
			int nowDayOfYear = now.get(Calendar.DAY_OF_YEAR);
			int bornDayOfYear = born.get(Calendar.DAY_OF_YEAR);
			System.out.println("nowDayOfYear:" + nowDayOfYear + " bornDayOfYear:" + bornDayOfYear);
			if (nowDayOfYear < bornDayOfYear) {
				age -= 1;
			}
		}
		return age;
	}

	// 保存前端新增的员工
	public boolean save(StaffEditDTO staffEditDTO) {
		Staff staff = new Staff();
		Department department = departmentRepository.findByDeptName(staffEditDTO.getDepartment());
		System.out.println(department);
		departmentRepository.addCount(department.getId());
		staff.setStaffName(staffEditDTO.getStaffName());
		staff.setPassword("123");
		staff.setSex(staffEditDTO.getSex());
		int age;
		age = getAgeByBirth(staffEditDTO.getBirthday());
		staff.setAge(age);
		staff.setPhone(staffEditDTO.getPhone());
		staff.setBirthday(staffEditDTO.getBirthday());
		staff.setAddress(staffEditDTO.getAddress());
		String education = convertEducation(staffEditDTO.getEducation());
		staff.setEducation(education);
		staff.setInTime(staffEditDTO.getInTime());
		staff.setHobby(staffEditDTO.getHobby());
		staff.setDepartment(department);
		staff.setPosition(staffEditDTO.getPosition());
		staff.setDepartment(department);// 双方建立关系
		department.getStaffs().add(staff);
		User user = new User();// 新增员工时设置员工的用户
		user.setUserName(staff.getStaffName());
		user.setPassword(staff.getPassword());
		user.setPhone(staff.getPhone());
		user.setDate(new Date());
		String res = userService.save(user);
		if (res == "用户名重复！") {
			return false;
		} else {
			staffRepository.save(staff);
			return true;
		}
	}

	// 更新前端提交的员工信息
	public void update(StaffEditDTO staffEditDTO) {
		Staff orignStaff = staffRepository.findOne(staffEditDTO.getId());
		// 更改部门的count字段，查找出所属的原来的部门人数-1，更改后的部门人数+1
		if (!orignStaff.getDepartment().getDeptName().equals(staffEditDTO.getDepartment())) {
			Department oldDept = departmentRepository.findByDeptName(orignStaff.getDepartment().getDeptName());
			oldDept.setCount(oldDept.getCount() - 1);
			Department newDept = departmentRepository.findByDeptName(staffEditDTO.getDepartment());
			newDept.setCount(newDept.getCount() + 1);
		}
		Staff staff;
		Department department = departmentRepository.findByDeptName(staffEditDTO.getDepartment());
		// System.out.println(department);
		staff = staffRepository.findOne(staffEditDTO.getId());
		staff.setStaffName(staffEditDTO.getStaffName());
		// staff.setPassword(staffEditDTO.getPassword());
		staff.setSex(staffEditDTO.getSex());
		staff.setAge(staffEditDTO.getAge());
		staff.setPhone(staffEditDTO.getPhone());
		staff.setBirthday(staffEditDTO.getBirthday());
		staff.setAddress(staffEditDTO.getAddress());
		String education = convertEducation(staffEditDTO.getEducation());
		staff.setEducation(education);
//		staff.setEducation(staffEditDTO.getEducation());
		staff.setInTime(staffEditDTO.getInTime());
		staff.setHobby(staffEditDTO.getHobby());
		staff.setDepartment(department);
		staff.setPosition(staffEditDTO.getPosition());
		staffRepository.save(staff);
	}

	// 删除员工
	public void delete(Staff staff) {
		staff = staffRepository.findOne(staff.getId());
		if (null != staff) {
			staff.getDepartment().setCount(staff.getDepartment().getCount() - 1);
			staff.setDepartment(null);
			staffRepository.save(staff);
			staffRepository.delete(staff);
		}
	}

	// 批量删除员工
	public void delete(List<Long> ids) {
		List<Staff> staffs = (List<Staff>) staffRepository.findAll(ids);
		if (null != ids && staffs != null) {
			for (Long id : ids) {
				staffRepository.findOne(id).getDepartment()
						.setCount(staffRepository.findOne(id).getDepartment().getCount() - 1);
			}
			for (Staff staff : staffs) {
				staff.setDepartment(null);
			}
			staffRepository.delete(staffs);
		}
		// if (staffs != null) {
		// }
	}

	// 查找单个员工
	@Transactional(readOnly = true)
	public Staff findOne(Long id) {
		return staffRepository.findOne(id);
	}

	// 查找所有员工
	@Transactional(readOnly = true)
	public List<Staff> findAll() {
		return (List<Staff>) staffRepository.findAll();
	}

	// 分页查询员工
	@Transactional(readOnly = true)
	@Override
	public Page<Staff> findPage(Specification<Staff> spec, Pageable pageable) {
		return staffRepository.findAll(spec, pageable);
	}

	// 通过部门ID查找人数
	@Override
	public int findByDeptId(Long id) {
		return staffRepository.findByDeptId(id);
	}

	// 批量导入
	@Override
	public boolean multiSave(List<Staff> staffLists) {
		for (Staff staff : staffLists) {
			Department department = new Department();
			User user = new User();// 新增员工时设置员工的用户
			user.setUserName(staff.getStaffName());
			user.setPassword(staff.getPassword());
			user.setPhone(staff.getPhone());
			user.setDate(new Date());
			String res = userService.save(user);
			if (res == "用户名重复！") {
				return false;
			} else {
				department = departmentRepository.findOne(staff.getDepartment().getId());
				staff.setDepartment(department);
				department.getStaffs().add(staff);
				staffRepository.save(staff);
				return true;
			}
		}
		return false;
	}

	@Override
	public int totalSex(String sex) {
		int sexCount = staffRepository.findBySex(sex);
		return sexCount;
	}

	// 通过员工名称查找该员工对象
	@Override
	public Staff findByStaffName(String staffName) {
		Staff staff = staffRepository.findByStaffName(staffName);
		return staff;
	}

	// 查找人事的最高领导，流程用到
	@Override
	public String findHRLeader() {
		Staff staff = staffRepository.findHRLeader();
		User user = userService.findByName(staff.getStaffName());// 查找出User表中与该部门领导对应的对象ID传给流程
		List<String> idListString = new ArrayList<String>();

		idListString.add(user.getUserName());
		return idListString.get(0);
	}

	// 查找部门领导，流程用到
	@Override
	public List<String> findDepartmentLeader(String userName) {// userName 为申请人的用户名

		Staff staff = staffRepository.findByStaffName(userName);// 找到申请人的对象
		Staff deptLeader = staffRepository.findDepartmentLeader(staff.getDepartment().getId());
		User user = userService.findByName(deptLeader.getStaffName());// 查找出User表中与该部门领导对应的对象传给流程
		List<String> idListString = new ArrayList<String>();

		idListString.add(user.getUserName());
		return idListString;
	}

	public List<Staff> findBySex2(String sex) {
		List<Staff> staffLists = staffRepository.findBySex2(sex);
		return staffLists;
	}
}
